package com.linjacy.httpproject.interceptor;


import com.linjacy.httpproject.entity.User;
import com.linjacy.httpproject.thread.UserHolder;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//@Intercepts(
//        {
//                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
//                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
//        }
//)
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class MybatisQueryInterceptor implements Interceptor {

    private static Logger logger = LoggerFactory.getLogger(MybatisQueryInterceptor.class);

    // 正则表达式
    private final Pattern pattern = Pattern.compile("\\{\\{[_A-Za-z0-9]+\\}\\}");

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = (StatementHandler)invocation.getTarget();
        BoundSql boundSql = statementHandler.getBoundSql();
        String sql = boundSql.getSql();

        Matcher matcher = this.pattern.matcher(sql);
        Set<String> ruleList = new HashSet<>();

        while(matcher.find()){
            ruleList.add(matcher.group());
        }

        if(ruleList.size() >0){
            for (String ruleString : ruleList) {
                String ruleGroupKey = ruleString.substring(2,ruleString.length()-2);
                sql = sql.replaceAll("\\{\\{"+ruleGroupKey+"\\}\\}", this.getRuleSql(ruleGroupKey));
            }
        }
        logger.info("增强后的sql为{}", sql);

        Field field = boundSql.getClass().getDeclaredField("sql");
        field.setAccessible(true);
        field.set(boundSql, sql);

        return invocation.proceed();
    }

    private String getRuleSql(String ruleGroupKey) {
        User user = UserHolder.getUser();
        if (user != null) {
            return "1 = 1";
        }else{
            return "1 != 1";
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
